<!DOCTYPE html>
<html lang="ZH-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.7, maximum-scale=1.0, user-scalable=no">
    <title>YYY system Control</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .joystick {
            width: 200px;
            height: 200px;
            background: rgb(204,204,255);
            border-radius: 15px;
            position: relative;
            margin: 20px;
        }
        .joystick-handle {
            width: 50px;
            height: 50px;
            background: rgb(253, 183, 207);
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            touch-action: none;
        }
        h1 {
            text-align: center;
            margin: 2px 0;
        }
        h4 {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        img {
            margin: 0 2px;
        }
    </style>
</head>
<body>
    <h3>
        BY: Yangyangyou-Zhang,洋洋柚<br>
        +_+ 共同研发项目<br>
        <a href="/stream"><input type="button" value="打开热成像" style="width: 200px; height: 50px;"></a>
        MDIT-TCLab
        <a href="/stream"><input type="button" value="打开地图" style="width: 200px; height: 50px;"></a><br>
    </h3>
    <h4>
        <div class="joystick" id="joystick1">
            <div class="joystick-handle"></div>
        </div>
        <img src="/stream" width="640" height="480">
        <div class="joystick" id="joystick2">
            <div class="joystick-handle"></div>
        </div>
    </h4>
    <script>
        let lastSendTime = 0;
        const SEND_INTERVAL = 100; //发送速度ms
        let pendingData = {};
        let sendTimeout = null;

        function setupJoystick(joystick, handle, id, sendDataCallback) {
            let activeTouchId = null;
            let isMouseDown =false;
            let currentRect = null;
            let initCounter = 2;

            // 增强型位置更新
            const updateRect = () => {
                currentRect = joystick.getBoundingClientRect();
                // 防止移动端浏览器布局异常
                if(initCounter < 3 && (!currentRect.width || currentRect.width === 0)) {
                    setTimeout(updateRect, 50);
                    initCounter++;
                }
            };

            // 统一输入处理
            const processStart = (input, isMouse) => {
                updateRect();
                if(isInJoystickArea(input)) {
                    if(isMouse) {
                        isMouseDown = true;
                    } else {
                        activeTouchId = input.identifier;
                    }
                    updatePosition(input);
                    return true;
                }
                return false;
            };

            // 优化触摸开始处理
            const handleTouchStart = (e) => {
                for(const touch of e.touches) {
                    if(!activeTouchId && processStart(touch, false)) {
                        e.preventDefault();
                        break;
                    }
                }
            };

            // 专用触摸移动处理
            const handleTouchMove = (e) => {
                //if(!activeTouchId) return;
                
                for(const touch of e.touches) {
                    if(touch.identifier === activeTouchId) {
                        updateRect();
                        updatePosition(touch);
                        e.preventDefault();
                        return;
                    }
                }
            };

            // 鼠标事件处理
            const handleMouseStart = (e) => {
                if(processStart(e, true)) {
                    e.preventDefault();
                }
            };

            const handleMouseMove = (e) => {
                if(isMouseDown) {
                    updatePosition(e);
                    e.preventDefault();
                }
            };

            // 通用结束处理
            const handleEnd = (e) => {
                if(e.type === 'mouseup') {
                    if(isMouseDown) {
                        resetControls();
                        sendDataCallback(0, 0);
                    }
                } else {
                    for(const touch of e.changedTouches) {
                        if(touch.identifier === activeTouchId) {
                            resetControls();
                            sendDataCallback(0, 0);
                            break;
                        }
                    }
                }
            };

            // 位置计算核⼼
            const updatePosition = (input) => {
                updateRect();
                const centerX = currentRect.left + currentRect.width/2;
                const centerY = currentRect.top + currentRect.height/2;
                
                let deltaX = input.clientX - centerX;
                let deltaY = input.clientY - centerY;
                const maxDist = currentRect.width/2;
                const distance = Math.sqrt(deltaX**2 + deltaY**2);

                if(distance > maxDist) {
                    deltaX = Math.max(-maxDist, Math.min(deltaX, maxDist));
                    deltaY = Math.max(-maxDist, Math.min(deltaY, maxDist));
                }

                handle.style.left = `${50 + (deltaX/maxDist)*50}%`;
                handle.style.top = `${50 + (deltaY/maxDist)*50}%`;

                sendDataCallback(
                    +(deltaX/maxDist).toFixed(2),
                    +(-deltaY/maxDist).toFixed(2)
                );
            };

            const isInJoystickArea = (input) => {
                return input.clientX >= currentRect.left && 
                    input.clientX <= currentRect.right &&
                    input.clientY >= currentRect.top &&
                    input.clientY <= currentRect.bottom;
            };

            const resetControls = () => {
                activeTouchId = null;
                isMouseDown = false;
                handle.style.left = '50%';
                handle.style.top = '50%';
            };

            // 初始化流程
            const initJoystick = () => {
                updateRect();
                // 三次异步位置验证
                [0, 100, 200].forEach(timeout => {
                    setTimeout(updateRect, timeout);
                });
            };

            // 事件绑定
            joystick.addEventListener('mousedown', handleMouseStart);
            joystick.addEventListener('touchstart', handleTouchStart, { passive: false });
            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('touchmove', handleTouchMove, { passive: false });
            document.addEventListener('mouseup', handleEnd);
            document.addEventListener('touchend', handleEnd);
            window.addEventListener('resize', updateRect);
            window.addEventListener('orientationchange', updateRect);

            initJoystick();
        }

        function sendJoystickData(id, x, y) {
            pendingData[`x${id}`] = x;
            pendingData[`y${id}`] = y;

            const now = Date.now();
            if(now - lastSendTime >= SEND_INTERVAL) {
                sendRequest();
                lastSendTime = now;
            } else {
                clearTimeout(sendTimeout);
                sendTimeout = setTimeout(() => {
                    sendRequest();
                    lastSendTime = Date.now();
                }, SEND_INTERVAL - (now - lastSendTime));
            }
        }

        function sendRequest() {
            if(Object.keys(pendingData).length === 0) return;

            fetch('/get_joystick_data', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(pendingData)
            }).catch(error => console.warn('Network error:', error));

            pendingData = {};
        }

        // 增强初始化
        const initJoysticks = () => {
            [1, 2].forEach(id => {
                const joystick = document.querySelector(`#joystick${id}`);
                const handle = joystick.querySelector('.joystick-handle');
                setupJoystick(joystick, handle, id, (x, y) => sendJoystickData(id, x, y));
            });
        };

        // 多重初始化保障
        if(document.readyState === 'complete') {
            initJoysticks();
        } else {
            window.addEventListener('load', initJoysticks);
            document.addEventListener('DOMContentLoaded', initJoysticks);
            setTimeout(initJoysticks, 1000);
        }
    </script>

</body>
</html>
